package com.wangshb.upms.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wangshb.upms.core.common.BeanMapper;
import com.wangshb.upms.core.common.PageRequest;
import com.wangshb.upms.core.tree.TreeNode;
import com.wangshb.upms.dto.PageResponseDto;
import com.wangshb.upms.dto.upms.permission.*;
import com.wangshb.upms.entity.UpmsPermission;
import com.wangshb.upms.service.UpmsPermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;


/**
 * @author auto code
 */
@RestController
public class UpmsPermissionController {

    @Autowired
    private UpmsPermissionService upmsPermissionService;


    @PostMapping("/upms/permission/listPage")
    public PageResponseDto listPage(@RequestBody PageRequest<UpmsPermissionQueryRequestDto> page) {
        Page<UpmsPermission> resultPage = this.upmsPermissionService.findPage(page.getPage(), page.getLimit(), BeanMapper.map(page.getCondition(), UpmsPermission.class));
        return PageResponseDto.builder().total(resultPage.getTotal()).data(BeanMapper.mapAsList(resultPage.getRecords(), UpmsPermissionQueryResponseDto.class)).build();
    }


    @PostMapping("/upms/permission/add")
    public Long addUpmsPermission(@RequestBody UpmsPermissionAddRequestDto addDto) {
        return this.upmsPermissionService.addUpmsPermission(BeanMapper.map(addDto, UpmsPermission.class));
    }


    @PostMapping("/upms/permission/edit")
    public void editUpmsPermission(@RequestBody UpmsPermissionEditRequestDto editDto) {
        this.upmsPermissionService.updateUpmsPermissionWithLock(BeanMapper.map(editDto, UpmsPermission.class));
    }


    @PostMapping("/upms/permission/del")
    public void delUpmsPermission(@RequestBody UpmsPermissionDelRequestDto delDto) {
        this.upmsPermissionService.delUpmsPermission(BeanMapper.map(delDto, UpmsPermission.class));
    }


    @PostMapping("/upms/permission/get")
    public UpmsPermissionGetResponseDto findById(@RequestBody UpmsPermissionGetRequestDto getDto) {
        QueryWrapper<UpmsPermission> upmsPermissionQueryWrapper = new QueryWrapper<>();
        upmsPermissionQueryWrapper.setEntity(BeanMapper.map(getDto, UpmsPermission.class));
        UpmsPermission upmsPermission = this.upmsPermissionService.getOne(upmsPermissionQueryWrapper);
        return null == upmsPermission ? null : BeanMapper.map(upmsPermission, UpmsPermissionGetResponseDto.class);
    }

    @PostMapping("/upms/permission/tree")
    public TreeNode treePermission() {
        return  TreeNode.listToTree(this.upmsPermissionService.findForPermissionTree());
    }
}
